//
//  SubSystemDetailViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/19/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "SubSystemDetailViewController.h"

@interface SubSystemDetailViewController ()

@end

@implementation SubSystemDetailViewController
@synthesize sections=_sections;
@synthesize subSystemNameSection=_subSystemNameSection;
@synthesize timePatternListSection=_timePatternListSection;
@synthesize timePatternList=_timePatternList;
@synthesize addtimePatternButton=_addtimePatternButton;
@synthesize subSystem=_subSystem;
@synthesize publicSender=_publicSender;
@synthesize subSystemNameTextView=_subSystemNameTextView;
@synthesize agency=_agency;
@synthesize intersectionList=_intersectionList;
@synthesize intersectionListSection=_intersectionListSection;
@synthesize linkButtonSection=_linkButtonSection;
@synthesize deleteIndexPath=_deleteIndexPath;
//@synthesize agencyNameSection=_agencyNameSection;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_subSystemNameSection release];
    [_timePatternListSection release];
    [_timePatternList release];
    [_addtimePatternButton release];
    [_subSystem release];
    [_subSystemNameTextView release];
    [_agency release];
    [_intersectionList release];
    [_intersectionListSection release];
    [_linkButtonSection release];
    [_deleteIndexPath release];
//    [_agencyNameSection release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.backgroundColor = [UIColor clearColor];
    //    UIImageView *backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];
    
    //    [self.navigationController.view addSubview:backgroundView];
    //    [self.navigationController.view sendSubviewToBack:backgroundView];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    //    [self.navigationController setNavigationBarHidden:YES animated:YES];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
//    if (!_agencyNameSection) {
//        _agencyNameSection=[[TableSection alloc]init];
//        
//        _agencyNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
//        [_agencyNameSection.contents addObject:self.agency.agencyName];
//        
//        _agencyNameSection.header=@"Agency Name";
//    }
    if (!_subSystemNameSection) {
        _subSystemNameSection=[[TableSection alloc]init];
     
        _subSystemNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_subSystemNameSection.contents addObject:self.subSystem.subSystemName];
        
        _subSystemNameSection.header=@"SubSystem Name";
    }
    if(!_timePatternListSection)
    {
        _timePatternListSection=[[TableSection alloc]init];
        self.timePatternList=[XMLParser getTimingPatternList:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        _timePatternListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.timePatternList.count; i++) {
            [_timePatternListSection.contents addObject:[[self.timePatternList objectAtIndex:i] timingPatternName]];
        }
        
        _timePatternListSection.header=@"Timing Pattern List";
    }
    if(!_intersectionListSection)
    {
        _intersectionListSection=[[TableSection alloc]init];
        self.intersectionList=[XMLParser getIntersectionList:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        _intersectionListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        
        for (int i=0; i<self.intersectionList.count; i++) {
            [_intersectionListSection.contents addObject:[[self.intersectionList objectAtIndex:i] intersectionName]];
        }
        
        
        _timePatternListSection.header=@"Intersection List";
    }
    if (!_linkButtonSection) {
        _linkButtonSection=[[TableSection alloc]init];
        _linkButtonSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_linkButtonSection.contents addObject:@"Link Lists"];
        
//        _timePatternListSection.header=@"Intersection List";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
//        [_sections addObject:self.agencyNameSection];
        [_sections addObject:self.subSystemNameSection];
        [_sections addObject:self.timePatternListSection];
        [_sections addObject:self.intersectionListSection];
//        [_sections addObject:self.linkButtonSection];
    }
    UITapGestureRecognizer *gestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewReturn:)] autorelease];
    gestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:gestureRecognizer];
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    UIBarButtonItem *mapButtonItem= [[[ UIBarButtonItem alloc ] initWithTitle: @"Map" style: UIBarButtonItemStyleBordered target: self action: @selector( goToMap:) ] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,mapButtonItem,space,nil ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.sections=nil;
    self.subSystemNameSection=nil;
    self.timePatternListSection=nil;
    self.timePatternList=nil;
    self.addtimePatternButton=nil;
    self.subSystem=nil;
    self.subSystemNameTextView=nil;
    self.agency=nil;
    self.intersectionList=nil;
    self.intersectionListSection=nil;
    self.linkButtonSection=nil;
    self.deleteIndexPath=nil;
//    self.agencyNameSection=nil;
}

- (void)viewWillAppear:(BOOL)animated
{
//    [self.navigationController setToolbarHidden:YES];
    [self updateViewController];
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.subSystem.subSystemName=self.subSystemNameTextView.text;
    [XMLParser updateSubSystem:self.subSystem agencyID:self.agency.agencyID];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;    
    cell.textLabel.text=sectionContentString;
    
    switch (indexPath.section) {
//        case 0:
//            cell.selectionStyle=UITableViewCellSelectionStyleNone;
////            [cell.textLabel setBackgroundColor:[UIColor grayColor]];
//            [cell setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
//            break;
        case 0:
        {
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
            self.subSystemNameTextView=[[[UITextView alloc] initWithFrame:CGRectMake(1, 5, (CONST_portraitCellWidth-2), (height-10))] autorelease];
            [self.subSystemNameTextView setText:sectionContentString];
            [self.subSystemNameTextView setFont:[TableSection TitleFont]];
            //            [self.projectNameTextView setTag:ProjectNameTextView];
            self.subSystemNameTextView.delegate=self;
            
            [[cell contentView] addSubview:self.subSystemNameTextView];
            [cell setBackgroundColor:[TableSection WhiteColor]];
            
            return cell;
        }
            
            break;
            
        default:
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
            break;
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    
    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
    aLabel.text =[[self.sections objectAtIndex:section] header] ;
    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
    aLabel.textAlignment = UITextAlignmentLeft;
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.textColor=[UIColor darkGrayColor];
    
    
    [headerView addSubview:aLabel];
    
    switch (section) {
        case 1:
        {
            //Then you can add a UILabel to your headerView
            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
            [newbutton setFrame:CGRectMake(180,4,30,30)];
            //    [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            [newbutton setTag:(section)];
            [newbutton addTarget:self action:@selector(clickAddTimingPatternButton:)
                forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:newbutton];
        }
            break;
        case 2:
        {
            //Then you can add a UILabel to your headerView
            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
            [newbutton setFrame:CGRectMake(180,4,30,30)];
            //    [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            [newbutton setTag:(section)];
            [newbutton addTarget:self action:@selector(clickAddIntersectionButton:)
                forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:newbutton];
        }
            break;
            
        default:
            break;
    }
    
//    if (section!=1) {
//        return headerView;
//    }
    
    
    return headerView;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (indexPath.section==0) {
        return UITableViewCellEditingStyleNone;
    }
    return UITableViewCellEditingStyleDelete;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        // Commit the delete
        self.deleteIndexPath=indexPath;
        switch (indexPath.section) {
            case 1:
            {
                [self removeTimePattern:indexPath.row];
            }
                break;
            case 2:
            {
                [self removeIntersection:indexPath.row];
            }
                break;
                
            default:
                break;
        }
        
        
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    
    
    return [[self.sections objectAtIndex:section] header];
    
}
#pragma mark - AlertView delegate
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        
        //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        if (!self.deleteIndexPath) {
            return;
        }
        switch (self.deleteIndexPath.section) {
            case 1:
            {
                int tag=self.publicSender;
                [XMLParser removeTimingPattern:[[self.timePatternList objectAtIndex:tag] timingPatternID] agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
                [self updateViewController];
            }
                break;
            case 2:
            {
//                int tag=self.publicSender;
                [XMLParser removeIntersection:[[self.intersectionList objectAtIndex:self.deleteIndexPath.row] intersectionID] agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
                [self updateViewController];
            }
                break;
                
            default:
                break;
        }
        
        
    } else {
        // be nice with the world, maybe initiate some Ecological action as a bonus
    }
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    switch (indexPath.section) {
        case 1:
        {
            TimingPatternDetailViewController *detailViewController=[[[TimingPatternDetailViewController alloc] initWithNibNameAndTimingPattern:@"TimingPatternDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:[self.timePatternList objectAtIndex:indexPath.row] bundle:nil] autorelease];
            [detailViewController setTitle:@"Timing Pattern"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
        case 2:
        {
            IntersectionDetailPage *detailViewController=[[[IntersectionDetailPage alloc] initWithNibNameAndIntersection:@"IntersectionDetailPage" agency:self.agency subSystem:self.subSystem intersection:[self.intersectionList objectAtIndex:indexPath.row] bundle:nil] autorelease];
            [detailViewController setTitle:@"Intersection Detail"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -TextView Delegate
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    self.subSystem.subSystemName=self.subSystemNameTextView.text;
    [XMLParser updateSubSystem:self.subSystem agencyID:self.agency.agencyID];
    self.subSystemNameSection=[[[TableSection alloc]init] autorelease];
    
    //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
    self.subSystemNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
    [self.subSystemNameSection.contents addObject:self.subSystem.subSystemName];
    
    self.subSystemNameSection.header=@"SubSystem Name";
    return YES;
}

#pragma mark - Customized functions
- (void) clickAddTimingPatternButton:(id)sender
{
    TimingPattern *timePattern=[[[TimingPattern alloc] init] autorelease];
    [timePattern setTimingPatternID:[XMLParser createTimingPatternID:self.agency.agencyID subSystemID:self.subSystem.subSystemID]];
    [timePattern setTimingPatternName:@"New Time Pattern"];
    [timePattern setCycleLength:@"100"];
    [XMLParser createTimingPattern:timePattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    [self updateViewController];
}
- (void) clickAddIntersectionButton:(id)sender
{
    Intersection *intersection=[[[Intersection alloc] init] autorelease];
    [intersection setIntersectionID:[XMLParser createIntersectionID:self.agency.agencyID subSystemID:self.subSystem.subSystemID]];
    [intersection setIntersectionName:@"New Intersection"];
    CLLocationCoordinate2D coordinate={0,0};
    [intersection setIntersectionCoordinate:coordinate];
    [XMLParser createIntersection:intersection agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    
//    for (int i=0; i<self.timePatternList.count; i++) {
//        TimingPattern *timingPattern=[self.timePatternList objectAtIndex:i];
//        Signal *signal=[[[NEMASignal alloc] initWithCycleLength:timingPattern.cycleLength] autorelease];
//        [signal setSignalID:intersection.intersectionID];
//        //    [signal setCycleLength:self.timingPattern.cycleLength];
//        [signal setOffset:@"0"];
//        [signal setSignalName:@"New Signal"];
//        [XMLParser createSignal:signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:timingPattern.timingPatternID];
//        
//    }
    
    
    
    [self updateViewController];
}
- (id) initWithNibNameAndSubSystem:(NSString *)nibName subSystem:(SubSystem *)subSystem agency:(Agency *)agency bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.subSystem=subSystem;
    self.agency=agency;
    return self;
}
- (IBAction)textViewReturn:(id)sender
{
    [self.subSystemNameTextView resignFirstResponder];
}
- (void) removeTimePattern: (int)row
{
    self.publicSender=row;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation" 
                                                    message:@"Delete the Time Pattern and its signals?" 
                                                   delegate:self 
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert show];
    [alert release];
}

- (void) removeIntersection: (int)row
{
    self.publicSender=row;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation"
                                                    message:@"Delete the intersection and its signal timings?"
                                                   delegate:self
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert show];
    [alert release];
}

- (void) updateViewController
{
//    if (self.agencyNameSection) {
//        self.agencyNameSection=[[TableSection alloc]init];
//        
//        self.agencyNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
//        [self.agencyNameSection.contents addObject:self.agency.agencyName];
//        
//        self.agencyNameSection.header=@"Agency Name";
//    }

    if (self.subSystemNameSection) {
        self.subSystemNameSection=[[[TableSection alloc]init] autorelease];
        
        self.subSystemNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.subSystemNameSection.contents addObject:self.subSystem.subSystemName];
        
        self.subSystemNameSection.header=@"SubSystem Name";
    }
    if(self.timePatternListSection)
    {
        self.timePatternListSection=[[[TableSection alloc]init] autorelease];
        self.timePatternList=[XMLParser getTimingPatternList:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        self.timePatternListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.timePatternList.count; i++) {
            [self.timePatternListSection.contents addObject:[[self.timePatternList objectAtIndex:i] timingPatternName]];
        }
        
        self.timePatternListSection.header=@"Timing Pattern List";
    }
    if(self.intersectionListSection)
    {
        self.intersectionListSection=[[[TableSection alloc]init] autorelease];
        self.intersectionList=[XMLParser getIntersectionList:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        self.intersectionListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.intersectionList.count; i++) {
            [self.intersectionListSection.contents addObject:[[self.intersectionList objectAtIndex:i] intersectionName]];
        }
        
        self.intersectionListSection.header=@"Intersection List";
    }
    if (self.sections) {
        self.sections = [[[NSMutableArray alloc] init] autorelease];
//        [self.sections addObject:self.agencyNameSection];
        [self.sections addObject:self.subSystemNameSection];
        [self.sections addObject:self.timePatternListSection];
        [self.sections addObject:self.intersectionListSection];
//        [self.sections addObject:self.linkButtonSection];
    }
    [self.tableView reloadData];
}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void) goToMap:(id)sender
{
    IntersectionExploreMapViewController *detailViewController=[[[IntersectionExploreMapViewController alloc] initWithNibNameAndTimingPattern:@"IntersectionExploreMapViewController" agency:self.agency subSystem:self.subSystem bundle:nil] autorelease];
    //    self.navigationItem.titleView=nil;
    //    [self.imageView removeFromSuperview];
    //    self.navigationItem.title=@"Home";
    [detailViewController setTitle:@"Intersection Map"];
    [self.navigationController pushViewController:detailViewController animated:YES];
}
@end
